package com.waldo.user.thrift;

import com.waldo.thrift.user.UserService;
import com.waldo.user.thrift.message.MessageService;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Auther: yelo
 * @Date: 2018/10/16 11:55
 * @Description:
 */
@Component
public class ServiceProvider {
    @Value("${thrift.message.ip}")
    private  String messageServcieIp;
    @Value("${thrift.message.port}")
    private int messageServicePort;
    @Value("${thrift.user.ip}")
    private  String userServcieIp;
    @Value("${thrift.user.port}")
    private int userServicePort;

    private  enum ServiceType{
        USER,
        MESSAGE;

    }
    public MessageService.Client getMessageService(){
        return  getService(messageServcieIp,messageServicePort,ServiceType.MESSAGE);
    }

    public UserService.Client getUserService(){
        return  getService(userServcieIp,userServicePort,ServiceType.MESSAGE);
    }

    protected  <T>T getService(String ip,int port ,ServiceType serviceType){
        TSocket socket = new TSocket(ip,port,3000);
        TTransport transport = new TFramedTransport(socket);
        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
            return  null;
        }
        TProtocol protocol = new TBinaryProtocol(transport);
        TServiceClient result = null;
        switch (serviceType){
            case MESSAGE:
                result =new  MessageService.Client(protocol);
            case USER:
                result = new UserService.Client(protocol);
                break;

        }
        return  (T) result;
    }

}
